package com.ics.cmsadmin.modules.basic.service.impl;

import com.ics.cmsadmin.frame.core.bean.PageBean;
import com.ics.cmsadmin.frame.core.bean.PageResult;
import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.enums.OrderStatusEnum;
import com.ics.cmsadmin.frame.core.enums.PayMethodEnum;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.frame.utils.KeyUtil;
import com.ics.cmsadmin.modules.basic.bean.CourseBean;
import com.ics.cmsadmin.modules.basic.bean.OrderBean;
import com.ics.cmsadmin.modules.basic.bean.StudentBean;
import com.ics.cmsadmin.modules.basic.service.CourseService;
import com.ics.cmsadmin.modules.basic.service.OrderService;
import com.ics.cmsadmin.modules.basic.service.StudentOrderService;
import com.ics.cmsadmin.modules.basic.service.StudentService;
import com.ics.cmsadmin.modules.pub.bean.CourseOrderVO;
import com.ics.cmsadmin.modules.pub.bean.OrderForm;
import com.ics.cmsadmin.modules.system.bean.RegisterBean;
import com.ics.cmsadmin.modules.system.service.RegisterService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class StudentOrderServiceImpl implements StudentOrderService {


    @Autowired
    private OrderService orderService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private RegisterService registerService;

    @Override
    public OrderBean create(OrderForm orderForm, String userId) {

        StudentBean student = studentService.queryById(userId);
        // 获取商品信息
        String productId = orderForm.getCourseId();
        CourseBean course = courseService.queryById(productId);
        if (course == null || !course.getIsActive()) {
            log.error("【创建订单 商品不存在或商品已下架");
            throw new CmsException(ApiResultEnum.PRODUCT_NOT_EXIST);
        }

        if (StringUtils.isBlank(userId)) {
            throw new CmsException(ApiResultEnum.UN_LOGIN);
        }

        // 根据openid 查询用户
        if (student == null) {
            throw new CmsException(ApiResultEnum.USER_NOT_EXIST);
        }

        if (StringUtils.isBlank(student.getOpenId())) {
            throw new CmsException(ApiResultEnum.PARAM_ERROR);
        }

        if (!student.getIsActive()) {
            throw new CmsException(ApiResultEnum.USER_NOT_ALLOW);
        }

        // 判断商品是否已经购买过
        boolean hadBought = orderService.getPurchaseStatus(student.getId(), productId);
        if (hadBought) {
            log.error("【创建订单】商品已购买，无需重复购买");
            throw new CmsException(ApiResultEnum.REPEAT_PURCHASE);
        }

        OrderBean order = new OrderBean();
        // 判断是否已经下单未支付
        OrderBean oldOrder = orderService.queryUserOrder(student.getId(), productId);
        boolean hasOrdered = oldOrder != null;
        if (hasOrdered) {
            order = oldOrder;
        } else {
            order.setId(KeyUtil.genUniqueKey());
            BeanUtils.copyProperties(orderForm, order);
            order.setOpenId(student.getOpenId());
        }
        // 设置课程原价
        order.setCoursePrice(course.getPrice());
        RegisterBean registerBean = registerService.queryById("global_price_discount");
        String globalDiscount = "1";
        if (null != registerBean) {
            globalDiscount = registerBean.getValue();
            Double globalDiscountValue = Double.valueOf(globalDiscount);
            if (!(globalDiscountValue>0&&globalDiscountValue<=1)){
                throw new CmsException(ApiResultEnum.GLOBAL_DISCOUNT_DISABLED);
            }
            log.info("We have global {} discount",globalDiscount);
        }
        // 设置订单金额
        BigDecimal price = course.getDiscountPrice();
        if (price == null || price.compareTo(BigDecimal.ZERO) == 0) {
            price = course.getPrice();
            if (price == null) {
                price = new BigDecimal(1);
            }
        }
        //再经过全局折扣价
        BigDecimal priceAfterGlobalDiscount = price.multiply(new BigDecimal(globalDiscount, new MathContext(2))).setScale(2, BigDecimal.ROUND_DOWN);
        order.setDiscountPrice(priceAfterGlobalDiscount);

        order.setOrderAmount(price);
        order.setStatus(OrderStatusEnum.WAIT.getCode());

        /* special vip start **/
        if (student.getSpecialVip()) {
            order.setOrderAmount(new BigDecimal(1.0));
        }
        /* special vip end **/
        // 默认使用微信支付
        order.setPaymentMethod(PayMethodEnum.WECHAT.getCode());
        order.setUserId(student.getId());
        order.setSalesman(student.getSalesman());
        order.setUserName(student.getUsername());
        order.setCourseName(course.getName());
        // 设置分销商信息
        order.setAgentNo(student.getAgentNo());
        boolean success;
        if (hasOrdered) {
            success = orderService.update(order);
        } else {
            success = orderService.insert(order);
        }
        if (!success) {
            log.error("【创建订单】插入订单数据失败，order = {}", order);
            throw new CmsException(ApiResultEnum.CREATE_ORDER_FAIL);
        }
        return order;
    }

    @Override
    public PageResult list(String userId, PageBean page) {
        PageResult pageResult = new PageResult();
        // 未登陆
        if (StringUtils.isEmpty(userId)) {
            pageResult.setDataList(new ArrayList<CourseOrderVO>());
            return pageResult;
        }
        PageResult orderResult = orderService.list(OrderBean.builder().userId(userId).status(OrderStatusEnum.SUCCESS.getCode()).build(), page);
        List<OrderBean> orderList = (List<OrderBean>) orderResult.getDataList();
        pageResult = courseService.purchased(userId, page);
        List<CourseBean> courseList = (List<CourseBean>) pageResult.getDataList();
        List<CourseOrderVO> courseOrderVOList = new ArrayList<>();
        for (int i = 0; i < courseList.size(); i++) {
            CourseOrderVO courseOrderVO = new CourseOrderVO();
            CourseBean course = courseList.get(i);
            courseOrderVO.setCourseId(course.getId());
            courseOrderVO.setCourseName(course.getName());
            courseOrderVO.setCoverSrc(course.getCoverSrc());
            courseOrderVO.setDescription(course.getDescription());

            OrderBean order = orderList.get(i);
            courseOrderVO.setOrderId(order.getId());
            courseOrderVO.setOrderAmount(order.getOrderAmount());
            courseOrderVO.setOrderType(order.getOrderType());
            Date payTime = order.getPayTime();
            if (payTime != null) {
                courseOrderVO.setOrderTime(payTime);
            } else {
                courseOrderVO.setOrderTime(order.getUpdateTime());
            }

            courseOrderVOList.add(courseOrderVO);
        }
        pageResult.setDataList(courseOrderVOList);
        return pageResult;
    }

}
